<?php

namespace App\Console\Commands\Cruise;

use App\Models\Cruise\CruiseCheckErrorModel;
use App\Models\Cruise\CruiseCheckSelfDetailModel;
use App\Models\Cruise\CruiseOrderInputModel;
use App\Models\Cruise\CruiseOrderInputTypeModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Service\Cruise\Check\CruiseCheckTaskService;
use App\Support\CustomForm\AttributeCruiseSupport;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class InitCruiseOrderInputType extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:init-cruise-order-input-type';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '稽核-初始化cruise order input type';


    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        CruiseOrderInputModel
            ::query()
            ->where('templateType', '!=', CruiseTemplateModel::TYPE_2)
            ->select('id', 'orderId', 'inputObjectJson', 'templateType')
            ->with('inputTypesRel')
            ->chunkById(100, function ($inputs) {
                $inputs->each(function (CruiseOrderInputModel $inputModel) {

                    if ($inputModel->inputTypesRel->count()) {
                        return;
                    }

                    $hitInputTypes = [];

                    // 至少有一个合格、不合格
                    foreach ($inputModel->inputObjectJsonArr as $projects) {
                        foreach ($projects['projects'] as $project) {
                            $projectObj = unserialize($project);
                            $inputType  = $projectObj->getInputType();


                            if (in_array($inputType, CruiseOrderInputTypeModel::SUPPORT_INPUT_TYPES)) {
                                $hitInputTypes[] = $inputType;
                            }
                        }
                    }

                    // 支持组件
                    if ($hitInputTypes) {
                        $hits = collect($hitInputTypes)->unique()->values()->map(function ($item) use ($inputModel) {
                            return [
                                'orderId'   => $inputModel->orderId,
                                'inputType' => $item,
                                'templateType' => $inputModel->templateType,
                            ];
                        })->toArray();

                        CruiseOrderInputTypeModel::query()->insert($hits);

                        $this->info("orderId: {$inputModel->orderId} done.");
                    }
                });
            });
    }
}
